package com.nuaa.ange.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nuaa.ange.annotation.ApiLog;
import com.nuaa.ange.common.lang.Consts;
import com.nuaa.ange.common.lang.RespBean;
import com.nuaa.ange.config.RabbitMqConfig;
import com.nuaa.ange.entity.Article;
import com.nuaa.ange.entity.User;
import com.nuaa.ange.rabbitmq.PostMqIndexMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.web.bind.annotation.*;


/**
 * @description
 * @author 玦离
 * @date 2022/12/30 22:08
 */

@RestController
@Api(tags = "文章相关接口")
@RequestMapping("/article")
@RequiredArgsConstructor
public class ArticleController extends BaseController{

    private final ObjectMapper objectMapper;
    private final AmqpTemplate amqpTemplate;

    @ApiOperation(value = "测试1")
    @GetMapping("/test01")
    @ApiLog
    public void test01()
    {
        System.out.println(getProfileId());
    }

    @ApiOperation(value = "发表编辑的初始界面")
    @GetMapping("/edit")
    @ApiLog
    public RespBean updateEditArticle() {
        Article draft = articleService.getDraftByAuthorId(getProfileId());
        if(draft != null) {
            return RespBean.ok("有草稿尚待编辑", draft);
        }
        return RespBean.error("无草稿");
    }

    @ApiOperation(value = "保存草稿")
    @PostMapping("/draft")
    @ApiLog
    public RespBean saveDraft(@RequestBody Article article) {
        Article draft = articleService.getDraftByAuthorId(getProfileId());
        if(draft != null) {
            article.setArticleId(draft.getArticleId());
            articleService.update(article, new UpdateWrapper<Article>()
                    .eq("article_id", draft.getArticleId()));
            return RespBean.ok("草稿已保存^▽^", draft.getArticleId());
        }
        else {
            int articleId = articleService.saveArticle(article, getProfileId(), 0);
            return RespBean.ok("草稿已保存^▽^", articleId);
        }
    }

    @ApiOperation(value = "发布仅自己可见文章")
    @PostMapping("/hiddenPublish")
    @ApiLog
    public RespBean hidePublishArticle(@RequestBody Article article) {
        Article draft = articleService.getDraftByAuthorId(getProfileId());
        if(draft != null) {
            // 如果是草稿编辑，将草稿内容删除
            articleService.removeById(draft.getArticleId());
        }
        int articleId = articleService.saveArticle(article, getProfileId(), 3);
        // TODO: 2023/1/2 能否返回主键
        return RespBean.ok("文章已发表为仅自己可见", articleId);
    }

    @ApiOperation(value = "发表文章")
    @PostMapping("/publish")
    @ApiLog
    public RespBean saveArticle(@RequestBody Article article) {
        Article draft = articleService.getDraftByAuthorId(getProfileId());
        // TODO: 2023/1/4 对于禁言用户直接删除无法保存草稿
        if(draft != null) {
            // 如果是草稿编辑，将草稿内容删除
            articleService.removeById(draft.getArticleId());
        }
        User author = userService.getById(getProfileId());
        // 发表后为发表状态
        article.setArticleState(1);
        article.setAuthorId(getProfileId());
        if (author.getUserState()) {
            articleService.save(article);
            // 通知消息给mq，告知添加
            try {
                amqpTemplate.convertAndSend(RabbitMqConfig.ES_EXCHANGE, RabbitMqConfig.ES_BIND_KEY,
                        objectMapper.writeValueAsString(new PostMqIndexMessage(article, PostMqIndexMessage.CREATE)));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return RespBean.ok("发表成功", article.getArticleId());
        }
        return RespBean.error("作者已被禁言");
    }

    @ApiOperation(value = "隐藏文章")
    @GetMapping("/hide")
    @ApiLog
    public RespBean updateHideArticle(@RequestParam("articleId") int articleId) {
        Article article = articleService.getById(articleId);
        article.setArticleState(3);
        return RespBean.ok("文章已仅自己可见");
    }

    @ApiOperation(value = "取消隐藏文章")
    @GetMapping("/open")
    @ApiLog
    public RespBean updateOpenArticle(@RequestParam("articleId") int articleId) {
        Article article = articleService.getById(articleId);
        User author = userService.getById(getProfileId());
        if (author.getUserState()) {
            article.setArticleState(1);
            return RespBean.ok("文章已取消隐藏成功");
        }
        return RespBean.error("您处于禁言状态，无法公开文章");
    }

    @ApiOperation(value = "重新编辑文章文章")
    @PostMapping("/update")
    @ApiLog
    public RespBean updateArticle(@RequestBody Article article) {
        User author = userService.getById(getProfileId());
        if (author.getUserState()) {
            // TODO: 2023/1/2 能否更新更新时间
            articleService.update(article, new UpdateWrapper<Article>()
                    .eq("article_id", article.getArticleId()));
            // 通知消息给mq，告知更新
            try {
                amqpTemplate.convertAndSend(RabbitMqConfig.ES_EXCHANGE, RabbitMqConfig.ES_BIND_KEY,
                        objectMapper.writeValueAsString(new PostMqIndexMessage(article, PostMqIndexMessage.UPDATE)));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return RespBean.ok("文章已重新编辑");
        }
        return RespBean.error("您已被禁言，无法重新编辑");
    }

    @ApiOperation(value = "删除文章")
    @GetMapping("/delete")
    @ApiLog
    public RespBean deleteArticle(@RequestParam("articleId") int articleId) {
        articleService.removeById(articleId);
        // 通知消息给mq，告知删除
        try {
            amqpTemplate.convertAndSend(RabbitMqConfig.ES_EXCHANGE, RabbitMqConfig.ES_BIND_KEY,
                    objectMapper.writeValueAsString(new PostMqIndexMessage(articleId, PostMqIndexMessage.REMOVE)));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return RespBean.ok("文章已删除");
    }

    @ApiOperation(value = "举报文章")
    @GetMapping("/reported")
    @ApiLog
    public RespBean updateArticleReported(@RequestParam("articleId") int articleId) {
        articleService.update(new UpdateWrapper<Article>()
                .eq("article_id", articleId)
                .setSql("'reported_num' = 'reported_num' + 1"));
        Article article = articleService.getById(articleId);
        // 举报次数 < 3
        if (article.getReportedNum() < Consts.REPORTED_NUM) {
            return RespBean.ok("举报成功");
        }
        // 将状态设为 2 ，即被举报
        article.setArticleState(2);
        // 举报次数 ≥ 3
        return RespBean.ok("帖子被禁");
    }
}
